package com.flow.framework.web.util;

import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.web.constant.FrameworkWebConstant;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Http servlet工具类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/12/25
 */
public class HttpServletUtil {

    /**
     * 将请求中的header提取到新的容器中
     *
     * @param httpServletRequest 请求
     * @return header
     */
    public static Map<String, List<String>> getAllHeaders(HttpServletRequest httpServletRequest) {
        if (VerifyUtil.isEmpty(httpServletRequest)) {
            return Collections.emptyMap();
        }
        Map<String, List<String>> result = new HashMap<>(16);
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            List<String> headerList = new ArrayList<>();
            String headerName = headerNames.nextElement();
            Enumeration<String> headers = httpServletRequest.getHeaders(headerName);
            while (headers.hasMoreElements()) {
                headerList.add(headers.nextElement());
            }
            result.put(headerName, headerList);
        }
        return result;
    }

    /**
     * 判断当前请求是否为rpc请求
     *
     * @param servletRequest 请求
     * @return 是否为rpc请求
     */
    public static boolean isRpcRequest(HttpServletRequest servletRequest) {
        String uri = servletRequest.getRequestURI();
        String forwardUri = (String) servletRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
        boolean isRpcForward = null != forwardUri && forwardUri.contains(FrameworkWebConstant.RPC_URI_CHARACTERISTIC);
        return isRpcForward || uri.contains(FrameworkWebConstant.RPC_URI_CHARACTERISTIC);
    }
}